package hotciv.view;

import hotciv.framework.*;

import java.awt.event.MouseEvent;

import minidraw.framework.*;
import minidraw.standard.*;

public class MoveUnitTool extends NullTool {
	
	// We wanna know the game and the editor, please! No cheating, give them to us!!
	private final DrawingEditor editor;
	private final Game game;
	
	// To remeber the figure, we are moving..
	private Figure figureToMove;
	// For the game moveUnit method
	private Position from;
	private Unit selectedUnit;
	// For moveBy
	private int lastX = 0;
	private int lastY = 0;
	
	public MoveUnitTool(DrawingEditor editor, Game game) {
		this.editor = editor;
		this.game = game;
	}

	@Override
	public void mouseDown(MouseEvent event, int x, int y) {
		from = GfxConstants.getPositionFromXY(x, y);
		if (!from.inWorld()) return;
		selectedUnit = game.getUnitAt(from);
		if (selectedUnit == null) return;
		figureToMove = editor.drawing().findFigure(x, y);
		lastX = x;
		lastY = y;
	}

	@Override
	public void mouseDrag(MouseEvent event, int x, int y) {
		if (figureToMove == null) return;
		figureToMove.moveBy(x-lastX,y-lastY);
		lastX = x;
		lastY = y;
	}

	@Override
	public void mouseUp(MouseEvent event, int x, int y) {
		figureToMove = null;
		if (selectedUnit != null) {
			Position to = GfxConstants.getPositionFromXY(x, y);
			if (to.inWorld()) {
				game.moveUnit(from, to);
			}
			else {
				game.moveUnit(from, from); // FAKE IT fix - så ens unit bliver rykket tilbage på plads..
			}
		}
		selectedUnit = null;
	}
}

